﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace AIC_PN
{
    public partial class BaoCaoMauBoSung1 : MyFromBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermission();
            if (!IsPostBack)
            {
                BindDataToControls();
                if (Request.QueryString["KyBaoCao"] != null)
                {
                    cboKyBaoCao.SelectedValue = Request.QueryString["KyBaoCao"];
                    cboKyBaoCao_SelectedIndexChanged(sender, e);
                }
            }
        }

        /// <summary>
        /// Thủ tục kiểm tra quyền sử dụng của người dùng có được quyền truy cập vào mục này hay không?
        /// </summary>
        private void CheckPermission()
        {
            Dictionary<string, int> Role = MyCommon.CheckPermission("BaoCaoMau1");
            if (Role == null || Role["Xem"] == 0 || ((Role["Xem"] == 1 && Role["Sua"] == 0)))
            {
                Response.Redirect("Index.aspx?p=0");
            }
        }

        /// <summary>
        /// Bind Data vào các contrls như Combobox, ListBox, textBox ...
        /// </summary>
        private void BindDataToControls()
        {
            //TODO
            if (Session["userid"] != null)
            {
                string sql = "Select DV.* " +
                             "From tblDonVi DV " +
                             "Inner Join tblUser U On U.DonViID=DV.ID " +
                             "Where U.ID=" + Session["userid"];
                DataTable dtDV = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
                tdTenDonVi.InnerHtml = "<b><i>Đơn vị báo cáo : " + dtDV.Rows[0]["TenDV"] + "</i></b>";
                sql = "Select ID,TenDM From tblDanhMuc Where MaDM='" + MyConst.DanhMuc.KyBaoCao.Ma + "' ";
                SqlDataReader reKyBaoCao = SqlHelper.ExecuteReader(CommandType.Text, sql);
                clsDataBind.CreateCombo("Tất cả", reKyBaoCao, cboKyBaoCao, 1, 0);
            }
        }

        #region Events

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("Index.aspx");
        }

        protected void cboKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboKyBaoCao.SelectedIndex <= 0)
            {
                btnLuu.Visible = false;
                pnl.Visible = false;
            }
            else
            {
                btnLuu.Visible = true;
                pnl.Visible = true;
                DataTable dt = KiemtraTonTai();
                if (dt.Rows.Count == 0)
                {
                    btnLuu.CommandName = MyConst.Action.Addnew;
                    ResetField();
                }
                else
                {
                    btnLuu.CommandName = MyConst.Action.Update;
                    BindDataToForm(dt);
                }
            }
        }

        private void ResetField()
        {
            txtF1.Text = "";
            txtF2.Text = "";
            txtF3.Text = "";
            txtF4.Text = "";
            txtF5.Text = "";
            txtF6.Text = "";
            lblTongSo.Text = "0";
        }

        private void BindDataToForm(DataTable dt)
        {
            txtF1.Text = dt.Rows[0]["F1"].ToString();
            txtF2.Text = dt.Rows[0]["F2"].ToString();
            txtF3.Text = dt.Rows[0]["F3"].ToString();
            txtF4.Text = dt.Rows[0]["F4"].ToString();
            txtF5.Text = dt.Rows[0]["F5"].ToString();
            txtF6.Text = dt.Rows[0]["F6"].ToString();
            lblTongSo.Text = dt.Rows[0]["F7"].ToString();
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {
            if (btnLuu.CommandName == MyConst.Action.Addnew)
            {
                AddnewBaoCao();
                DataTable dt = KiemtraTonTai();
                BindDataToForm(dt);
            }
            else
            {
                UpdateBaoCao();
                DataTable dt = KiemtraTonTai();
                BindDataToForm(dt);
            }
        }

        #endregion Events

        #region CRUD BaoCao

        protected void AddnewBaoCao()
        {
            string sSQL = "INSERT INTO [dbo].[tblBaoCaoBoSung1]([KyBaoCaoID_DM],[DonViID],[F1],[F2],[F3],[F4],[F5],[F6],[F7] " +
                            ",[CM_TenBaoCao],[CM_ThoiGianBaoCao],[CreateDate],[UpdateDate],[UserID])VALUES " +
                            "(@KyBaoCaoID_DM,@DonViID,@F1,@F2,@F3,@F4,@F5,@F6,(@F4+@F5+@F6) " +
                            ",@CM_TenBaoCao,CONVERT(NVARCHAR(10),GETDATE(),103),GETDATE(),GETDATE(),@UserID)";

            List<SqlParameter> lstParameter = new List<SqlParameter>();
            lstParameter.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, Convert.ToInt32(cboKyBaoCao.SelectedValue)));
            lstParameter.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, Session["userdonvi"]));
            lstParameter.Add(SqlHelper.CreateParameterObject("@F1", SqlDbType.NVarChar, ParameterDirection.Input, txtF1.Text.Trim()));
            lstParameter.Add(SqlHelper.CreateParameterObject("@F2", SqlDbType.NVarChar, ParameterDirection.Input, txtF2.Text.Trim()));
            lstParameter.Add(SqlHelper.CreateParameterObject("@F3", SqlDbType.NVarChar, ParameterDirection.Input, txtF3.Text.Trim()));
            lstParameter.Add(SqlHelper.CreateParameterObject("@F4", SqlDbType.Float, ParameterDirection.Input, txtF4.Text.Trim().Equals("") ? "0" : txtF4.Text.Trim()));
            lstParameter.Add(SqlHelper.CreateParameterObject("@F5", SqlDbType.Float, ParameterDirection.Input, txtF5.Text.Trim().Equals("") ? "0" : txtF5.Text.Trim()));
            lstParameter.Add(SqlHelper.CreateParameterObject("@F6", SqlDbType.Float, ParameterDirection.Input, txtF6.Text.Trim().Equals("") ? "0" : txtF6.Text.Trim()));
            lstParameter.Add(SqlHelper.CreateParameterObject("@CM_TenBaoCao", SqlDbType.NVarChar, ParameterDirection.Input, txtTenBaoCao.Text.Trim()));
            lstParameter.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Session["userid"]));


            int result = SqlHelper.ExecuteNonQuery(CommandType.Text, sSQL, lstParameter);
            if (result > 0)
            {
                MyCommon.AddMessage(this.Master, "Thêm mới báo cáo thành công !", MyConst.MessageType.Success);
                btnLuu.CommandName = MyConst.Action.Update;
            }
            else
            {
                MyCommon.AddMessage(this.Master, "Thêm mới báo cáo xảy ra lỗi !", MyConst.MessageType.Error);
            }
        }

        protected void UpdateBaoCao()
        {
            string sSQL = "UPDATE dbo.tblBaoCaoBoSung1 SET F1=@F1,F2=@F2,F3=@F3,F4=@F4, " +
                          "F5=@F5,F6=@F6,F7=@F4+@F5+@F6,CM_TenBaoCao = @CM_TenBaoCao,UpdateDate = GETDATE()," +
                          "UserID = @UserID WHERE KyBaoCaoID_DM = @KyBaoCaoID_DM AND DonViID = @DonViID";

            List<SqlParameter> lstParameter = new List<SqlParameter>();
            lstParameter.Add(SqlHelper.CreateParameterObject("@F1", SqlDbType.NVarChar, ParameterDirection.Input, txtF1.Text.Trim()));
            lstParameter.Add(SqlHelper.CreateParameterObject("@F2", SqlDbType.NVarChar, ParameterDirection.Input, txtF2.Text.Trim()));
            lstParameter.Add(SqlHelper.CreateParameterObject("@F3", SqlDbType.NVarChar, ParameterDirection.Input, txtF3.Text.Trim()));
            lstParameter.Add(SqlHelper.CreateParameterObject("@F4", SqlDbType.Float, ParameterDirection.Input, txtF4.Text.Trim().Equals("") ? "0" : txtF4.Text.Trim()));
            lstParameter.Add(SqlHelper.CreateParameterObject("@F5", SqlDbType.Float, ParameterDirection.Input, txtF5.Text.Trim().Equals("") ? "0" : txtF5.Text.Trim()));
            lstParameter.Add(SqlHelper.CreateParameterObject("@F6", SqlDbType.Float, ParameterDirection.Input, txtF6.Text.Trim().Equals("") ? "0" : txtF6.Text.Trim()));
            lstParameter.Add(SqlHelper.CreateParameterObject("@CM_TenBaoCao", SqlDbType.NVarChar, ParameterDirection.Input, txtTenBaoCao.Text.Trim()));
            lstParameter.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Session["userid"]));
            lstParameter.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, Convert.ToInt32(cboKyBaoCao.SelectedValue)));
            lstParameter.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, Session["userdonvi"]));


            int result = SqlHelper.ExecuteNonQuery(CommandType.Text, sSQL, lstParameter);
            if (result > 0)
            {
                MyCommon.AddMessage(this.Master, "Cập nhật báo cáo thành công !", MyConst.MessageType.Success);
                btnLuu.CommandName = MyConst.Action.Update;
            }
            else
            {
                MyCommon.AddMessage(this.Master, "Cập nhật báo cáo xảy ra lỗi !", MyConst.MessageType.Error);
            }

        }

        protected void XoaBaoCao(int ID)
        {
            string sSQL = "DELETE FROM dbo.tblBaoCaoBoSung1 WHERE KyBaoCaoID_DM = @KyBaoCaoID_DM AND DonViID = @DonViID";

            List<SqlParameter> lstParameter = new List<SqlParameter>();
            lstParameter.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, Convert.ToInt32(cboKyBaoCao.SelectedValue)));
            lstParameter.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, Session["userdonvi"]));


            int result = SqlHelper.ExecuteNonQuery(CommandType.Text, sSQL, lstParameter);
            if (result > 0)
            {
                MyCommon.AddMessage(this.Master, "Xóa báo cáo thành công !", MyConst.MessageType.Success);
            }
            else
            {
                MyCommon.AddMessage(this.Master, "Xóa báo cáo xảy ra lỗi !", MyConst.MessageType.Error);
            }
        }

        protected DataTable KiemtraTonTai()
        {
            string sSQL = "SELECT * FROM dbo.tblBaoCaoBoSung1 WHERE KyBaoCaoID_DM = @KyBaoCaoID_DM AND DonViID = @DonViID";

            List<SqlParameter> lstParameter = new List<SqlParameter>();
            lstParameter.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, Convert.ToInt32(cboKyBaoCao.SelectedValue)));
            lstParameter.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, Session["userdonvi"]));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sSQL, lstParameter);

            return dt;
        }
        #endregion

    }
}
